package handlers

import (
	"car_order/cache"
	"car_order/models"
	"car_order/pkg"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "不能为空",
		})
		return
	}
	redis_key := "redis_key_" + username
	cache_data, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if cache_data >= 3 {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "密码错误3次",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username = ?", username).Debug().First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "用户名不存在",
		})
		return
	}
	if user.Password != pkg.Md5str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if cache_data == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 0,
				"msg":  "密码错误3次，封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
		"data": user,
	})
	return
}

func RoleAddNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))

	data := models.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	models.DB.Create(&data)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": data,
	})
	return
}
func UserRole(c *gin.Context) {
	uid := c.Query("uid")
	var data []models.Role
	/*
		SELECT
		  *
		FROM
		  roles
		  LEFT JOIN user_roles ON user_roles.rid = roles.id
		WHERE
		  user_roles.uid = 1
	*/
	models.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON user_roles.rid = roles.id").
		Where("user_roles.uid = ?", uid).Debug().First(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": data,
	})
	return

}
func RoleNode(c *gin.Context) {
	rid := c.Query("rid")
	var data []models.Node
	/*
		SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN role_nodes ON role_nodes.nid = nodes.id
		WHERE
		  role_nodes.rid = 1
	*/
	models.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON role_nodes.nid = nodes.id").
		Where("role_nodes.rid = ?", rid).Debug().First(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": data,
	})
	return
}
